package org.itli.jnsocket.Controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.itli.jnsocket.Pojo.Goods;
import org.itli.jnsocket.Result.Result;
import org.itli.jnsocket.Service.NGoodsService;
import org.itli.jnsocket.Util.JWTUtil;
import org.itli.jnsocket.Util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.Map;

@Slf4j
@Tag(name = "商品接口")
@RequestMapping("/NGoods")
@RestController
public class NGoodsController {
    NGoodsService service;

    JWTUtil jwt = new JWTUtil();

    @Autowired
    public void setService(NGoodsService service) {
        this.service = service;
    }

    //查询所有商品数据
    @PostMapping("/AllGoods")
    @Operation(summary = "查询所有商品")
    public Result<String> AllGoods(@RequestBody PageUtil page) {
        String s = service.AllGoods(page);
        return Result.success(s);
    }

    //根据仓库id 获取仓库内的商品
    @PostMapping("/GoodsInWarehouse")
    @Operation(summary = "查询特定仓库中的所有信息")
    public Result<String> GoodsInWarehouse(@RequestBody Goods goods) {
        log.info("接收到数据"+goods);
        String s = service.GoodsInWarehouse(BigInteger.valueOf(goods.getWarehouse_id()));
        return Result.success(s);
    }


    //查询某个商品详细信息
    @PostMapping("/GetGoods")
    @Operation(summary = "查询特定商品")
    public Result<String> GetGoods(@RequestBody Goods goods) {
        log.info("前端传来数据"+goods.getGoods_sn());
        String s = service.GetGoods(goods.getGoods_sn());
        return Result.success(s);
    }


    //编辑商品
    @PostMapping("/UpdateGoods")
    @Operation(summary = "编辑商品")
    public Result<String> UpdateGoods(@RequestHeader("Authorization") String token,@RequestBody Goods goods) {
        log.info("收到前端："+goods);
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");
        String s = service.UpdateGoods(goods, username);
        return Result.success(s);
    }

    //添加商品
    @PostMapping("/AddGoods")
    @Operation(summary = "添加商品")
    public Result<String> AddGoods(@RequestHeader("Authorization") String token,@RequestBody Goods goods) {
        log.info("收到前端："+goods);
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");
        goods.setGoods_status("上架");
        String s = service.AddGoods(goods, username);
        return Result.success(s);
    }

}
